package com.lanmaoly.web.server.controller;

import com.lanmaoly.web.server.entity.Result;
import com.lanmaoly.web.server.entity.UserDetailsEntity;
import com.lanmaoly.web.server.pojo.TbUser;
import com.lanmaoly.web.server.service.AddressService;
import com.lanmaoly.web.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private AddressService addressService;

    @RequestMapping("/details")
    public String details(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        TbUser tbUser = userService.selectByName(name);
        model.addAttribute("username", authentication.getName());
        model.addAttribute("isLogin", true);
        model.addAttribute("tbUser", tbUser);
        return "portal/home-setting-info";
    }

    @RequestMapping("/update")
    @ResponseBody
    public Result update(TbUser tbUser) {
        UserDetailsEntity principal = (UserDetailsEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        tbUser.setId(principal.getId());
        tbUser.setUpdated(new Date());
        userService.update(tbUser);
        return Result.success();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @RequestMapping("/repassword")
    @ResponseBody
    public Result repassword(String password) {
        UserDetailsEntity principal = (UserDetailsEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        TbUser tbUser = new TbUser();
        tbUser.setId(principal.getId());
        tbUser.setUpdated(new Date());
        tbUser.setPassword(passwordEncoder.encode(password));
        userService.update(tbUser);
        return Result.success();
    }
}
